package com.zjhn.ds.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjhn.ds.common.BizResult;
import com.zjhn.ds.common.PageResult;
import com.zjhn.ds.domain.dto.pc.*;
import com.zjhn.ds.domain.entity.erp.Department;
import com.zjhn.ds.domain.entity.erp.Operator;
import com.zjhn.ds.domain.entity.jlw.*;
import com.zjhn.ds.domain.vo.SpinnerVo;
import com.zjhn.ds.mapper.*;
import com.zjhn.ds.param.GetOperatorPageParam;
import com.zjhn.ds.param.GetSpinnerPageParam;
import com.zjhn.ds.param.GetStationPageParam;
import com.zjhn.ds.service.CommonService;
import com.zjhn.ds.utils.CommonUtil;
import com.zjhn.ds.utils.base.CustomUtil;
import com.zjhn.ds.utils.base.DateUtil;
import com.zjhn.ds.utils.EntityTransformUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.service.impl
 * @Author: sxt
 * @CreateTime: 2023-09-09  08:08
 * @Description:
 * @Version: 1.0
 */
@Service
public class CommonServiceImpl implements CommonService {

    @Resource
    private CommonUtil commonUtil;

    @Resource
    private EntityTransformUtil entityTransformUtil;

    @Resource
    private OperatorMapper operatorMapper;

    @Resource
    private SpinnerMapper spinnerMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private GroupSpinnerMapper groupSpinnerMapper;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private EquipmentTypeMapper equipmentTypeMapper;

    @Resource
    private ModelMapper modelMapper;

    /**
     * 按条件分页查询不是挡车工的员工信息
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<OperatorDto>> getOperatorsPage(GetOperatorPageParam param) {
        List<Spinner> spinners = spinnerMapper.selectList(new QueryWrapper<Spinner>().select("operate_id"));
        Set<String> spinnerIds = new HashSet<>();
        if (spinners.size()>0)
            spinnerIds.addAll(spinners.stream().map(Spinner::getOperateId).collect(Collectors.toSet()));

        String search = param.getSearch();
        // 条件约束
        QueryWrapper<Operator> queryWrapper =
                new QueryWrapper<Operator>()
                        .eq("IsDeleted", 0)
                        .notIn("id",spinnerIds);
        if (StringUtils.isNotBlank(param.getDepartmentId())){
            // 获取当前部门id 及 子部门id
            List<Department> departments = departmentMapper.selectList(new QueryWrapper<>());
            List<String> ids = new ArrayList<>();
            ids.add(param.getDepartmentId());
            CustomUtil.getDepartmentSon(ids, param.getDepartmentId(), departments);
            queryWrapper.in("DepartmentGuid", ids);
        }
        if (StringUtils.isNotBlank(search))
            // 搜索条件
            queryWrapper.and(qr -> qr.like("RealName", search).or().like("UserNo", search));

        IPage<Operator> page = operatorMapper.selectPage(
                new Page<>(param.getCurrent(), param.getSize()),
                queryWrapper.orderByAsc("DepartmentGuid").orderByAsc("RealName"));
        IPage<OperatorDto> convert = page.convert(c -> OperatorDto.builder()
                .operateId(c.getId())
                .realName(c.getRealName())
                .username(c.getUsername())
                .userNo(c.getUserNo())
                .department(commonUtil.getDepartmentId(c.getDepartmentGuid()))
                .build());

        return BizResult.success(PageResult.<OperatorDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 按条件分页查询车间未绑定挡车工信息
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<SpinnerDto>> getSpinnerPage(GetSpinnerPageParam param) {
        // 不用租户判断 车间id唯一
        List<String> spinnerId = groupSpinnerMapper.getByWorkshopId(param.getWorkshopId());

        IPage<SpinnerVo> spinnerPage = spinnerMapper.getSpinnerPage(
                new Page<>(param.getCurrent(), param.getSize()),
                param.getSearch(),
                spinnerId,
                param.getWorkshopId()
        );

        IPage<SpinnerDto> convert = spinnerPage.convert(
                c -> SpinnerDto.builder()
                        .spinnerId(c.getSpinnerId())
                        .userNo(c.getUserNo())
                        .username(c.getUsername())
                        .realName(c.getRealName())
                        .createTime(DateUtil.formatDateToString(c.getCreateTime()))
                        .department(commonUtil.getDepartmentId(c.getDepartmentId()))
                        .build());

        return BizResult.success(PageResult.<SpinnerDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 按条件分页查询车间未绑定工位信息
     * @param param
     * @return
     */
    @Override
    public BizResult<PageResult<WorkShopStationDto>> getStationPage(GetStationPageParam param) {
        QueryWrapper<Station> queryWrapper = new QueryWrapper<Station>().eq("workshop_id", param.getWorkshopId());
        if (StringUtils.isNotBlank(param.getStationCode()))
            queryWrapper.like("station_code", param.getStationCode());

        IPage<Station> stationPage = stationMapper.selectPage(
                new Page<>(param.getCurrent(), param.getSize()),
                queryWrapper.orderByAsc("line_number","column_number","station_code")
        );

        IPage<WorkShopStationDto> convert = entityTransformUtil.workshopStationDtoChange(stationPage);

        return BizResult.success(PageResult.<WorkShopStationDto>builder()
                .current(convert.getCurrent())
                .pages(convert.getPages())
                .size(convert.getSize())
                .record(convert.getRecords())
                .build());
    }

    /**
     * 查询设备类别列表
     * @return
     */
    @Override
    public BizResult<List<EquipmentTypeDto>> getTypeList() {
        List<EquipmentTypeDto> res = new ArrayList<>();
        List<EquipmentType> equipmentTypes = equipmentTypeMapper.selectList(new QueryWrapper<>());
        if (equipmentTypes.size() > 0)
            res.addAll(equipmentTypes.stream()
                    .map(c -> EquipmentTypeDto.builder()
                            .typeId(c.getId())
                            .typeName(c.getTypeName())
                            .createTime(DateUtil.formatDateToString(c.getCreateTime()))
                            .build()).collect(Collectors.toList()));
        return BizResult.success(res);
    }

    /**
     * 查询模型列表
     * @return
     */
    @Override
    public BizResult<List<ModelDto>> getModelList() {
        List<ModelDto> res = new ArrayList<>();
        List<Model> models = modelMapper.selectList(new QueryWrapper<>());
        if (models.size() > 0)
            res.addAll(models.stream()
                    .map(c -> ModelDto.builder()
                            .modelId(c.getId())
                            .modelName(c.getModelName())
                            .modelCode(c.getModelCode())
                            .needleNumber(c.getNeedleNumber())
                            .needleCode(c.getNeedleCode())
                            .stockingsCode(c.getStockingsCode())
                            .createTime(DateUtil.formatDateToString(c.getCreateTime()))
                            .build()).collect(Collectors.toList()));
        return BizResult.success(res);
    }

}
